import CryptoJS from "crypto-js";
import keyConfig from "../config/key";

const key = CryptoJS.enc.Utf8.parse(keyConfig.key); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse(keyConfig.iv); //十六位十六进制数作为密钥偏移量

//加密方法
function encrypt(data) {
  const encrypted = CryptoJS.AES.encrypt(data, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.ciphertext.toString().toUpperCase();
}

//解密方法
function decrypt(data) {
  let encryptedHexStr = CryptoJS.enc.Hex.parse(data);
  let encrypted = CryptoJS.enc.Base64.stringify(encryptedHexStr);
  let decrypt = CryptoJS.AES.decrypt(encrypted, key, {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypt.toString(CryptoJS.enc.Utf8);
}

export default {
  decrypt,
  encrypt
};
